package com.example.distinguish_server.Utils.ThreadCache;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
 public class TimedCache<K, V> {
    private final Map<K, V> cache;
    private final ScheduledExecutorService executorService;
    private long expirationTime;

     public long getExpirationTime() {
         return expirationTime;
     }

     public void setExpirationTime(long expirationTime) {
         this.expirationTime = expirationTime;
     }

     public TimedCache(long expirationTime) {
        this.cache = new ConcurrentHashMap<>();
        this.executorService = Executors.newScheduledThreadPool(1);
        this.expirationTime = expirationTime;
    }
     public void put(K key, V value) {
        cache.put(key, value);
        scheduleRemoval(key);
    }
     public V get(K key) {
        return cache.get(key);
    }
     public void remove(K key) {
        cache.remove(key);
    }
     private void scheduleRemoval(K key) {
        executorService.schedule(() -> cache.remove(key), expirationTime, TimeUnit.MILLISECONDS);
    }
}